package com.zzb.framework.modules.dict.service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Charsets;
import com.zzb.framework.common.BaseResponse;
import com.zzb.framework.common.BaseService;
import com.zzb.framework.common.FrameworkException;
import com.zzb.framework.modules.dict.dao.SysDictDAO;
import com.zzb.framework.modules.dict.entity.SysDict;
import com.zzb.framework.modules.role.entity.SysUserEntity;
import com.zzb.framework.validator.annotation.ValidatorEnabled;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.TreeMap;

/**
 * 数据字典 service类
 */
@Service
public class SysDictService extends BaseService<SysDictDAO, SysDict> {
    private static final Logger logger = LoggerFactory.getLogger(SysDictService.class);
    @Autowired
    private SysDictDAO sysDictDAO;

    @Override
    public SysDictDAO getDAO() {
        return sysDictDAO;
    }

    /**
     * 删除数据字典
     */
    public BaseResponse deleteSysDict(String id, SysUserEntity operate) throws FrameworkException {
        return deleteById(id);
    }

    /**
     * 保存数据字典
     */
    @ValidatorEnabled
    public BaseResponse<SysDict> saveSysDict(SysDict sysDict, SysUserEntity operator) throws FrameworkException {
        logger.info("正在保存数据字典[" + JSON.toJSONString(sysDict) + "][" + JSON.toJSONString(operator) + "]");
        return insertOrUpdate(sysDict, operator);
    }

    /**获取数据字典列表*/
    public List<SysDict> findByParamKey(String paramKey){
        return getDAO().getMapper().selectList(new QueryWrapper<SysDict>().eq("param_key",paramKey));
    }

    public BaseResponse<File> generatorJSONFile(String fileName){
        HashMap<String, TreeMap<String, String>> sysDictMap = generatorJSON();
        String json = "var dict="+JSON.toJSONString(sysDictMap)+";";
        File file = new File(fileName);
        try {
            FileUtils.write(file,json, Charsets.UTF_8,false);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new BaseResponse<>(BaseResponse.SUCCESS,"生成json成功",file);
    }

    public HashMap<String, TreeMap<String, String>> generatorJSON() {
        List<SysDict> sysDicts = getDAO().getMapper().selectList(new QueryWrapper<SysDict>().orderBy(true,true,"param_order"));
        //聚合成一个hashmap
        return sysDicts.stream().collect(HashMap::new,
                (map, sysDict) -> {
                    TreeMap<String,String> sysDictValueMap ;
                    if (map.containsKey(sysDict.getParamKey())) {
                        sysDictValueMap = map.get(sysDict.getParamKey());
                    } else {
                        sysDictValueMap = new TreeMap<>();
                        map.put(sysDict.getParamKey(),sysDictValueMap);
                    }
                    sysDictValueMap.put(sysDict.getParamValue(),sysDict.getValueComment());
                },(map, map2) -> map2.forEach((key, value) -> {
                    map.putIfAbsent(key, value);
                    map.computeIfPresent(key,(s, valueMap) -> {
                        valueMap.putAll(value);
                        return valueMap;
                    });
                })
        );
    }
}
